package slicegen;

import javax.media.j3d.BoundingBox;
import javax.media.j3d.Geometry;
import javax.media.j3d.GeometryArray;
import javax.media.j3d.Shape3D;
import javax.media.j3d.Transform3D;
import javax.vecmath.Point3d;
import javax.vecmath.Vector3d;

public class Solid extends Shape3D
{
	public Solid()
	{
		super();
	}
	
	public Solid(Geometry g)
	{
		super(g);
	
		Point3d lower = new Point3d(), upper = new Point3d();

		((BoundingBox) getBounds()).getLower(lower);
		((BoundingBox) getBounds()).getUpper(upper);
		
		minZ = lower.z;
		maxZ = upper.z;
		
		System.out.println("const: " + minZ + " " + maxZ);
	}
	
	@Override
	public void setGeometry(Geometry arg0)
	{
		super.setGeometry(arg0);
		
		Point3d lower = new Point3d(), upper = new Point3d();

		((BoundingBox) getBounds()).getLower(lower);
		((BoundingBox) getBounds()).getUpper(upper);
		
		minZ = lower.z;
		maxZ = upper.z;
		
		System.out.println("const: " + minZ + " " + maxZ);
	}
	
	public FacetList generateFacetList()
	{
		FacetList facets = new FacetList();
		
		GeometryArray geometry = (GeometryArray) getGeometry();
		
		int numVertices = geometry.getVertexCount();
		
		Point3d p1 = new Point3d(), p2 = new Point3d(), p3 = new Point3d();
		
		for (int i = 0; i < numVertices; i+=3)
		{
			geometry.getCoordinate(i, p1);
			geometry.getCoordinate(i+1, p2);
			geometry.getCoordinate(i+2, p3);
			
			facets.add(new Triangle(p1, p2, p3));
		}
		
		return facets;
	}
	
	/**
	 * Move the lower bound to (0,0,0)
	 * Scale the model to a cube of BOUNDING_CUBE_SIZE
	 */
	public void normalizeModel()
	{
		BoundingBox bounds = (BoundingBox) getBounds();
		
		System.out.println(bounds);
		
		Point3d lower = new Point3d(), upper = new Point3d(), size = new Point3d();
		
		bounds.getLower(lower);
		bounds.getUpper(upper);
		
		Transform3D translate = new Transform3D(), scale = new Transform3D();
		translate.setTranslation(new Vector3d(-lower.x, -lower.y, -lower.z));
		
		size.sub(upper, lower);
		
		//Size is now the size of the object from (0,0,0)
		
		double maxDimension = Math.max(size.x, Math.max(size.y, size.z));
		
		System.out.println(maxDimension);
				
		scale.setScale(BOUNDING_CUBE_SIZE / maxDimension);
		
		GeometryArray geom = (GeometryArray) getGeometry();
		
		Point3d point = new Point3d();
		for (int i = 0; i < geom.getVertexCount(); i++)
		{
			geom.getCoordinate(i, point);
			translate.transform(point);
			scale.transform(point);
			geom.setCoordinate(i, point);
		}
		
		((BoundingBox) getBounds()).getLower(lower);
		((BoundingBox) getBounds()).getUpper(upper);
		
		minZ = lower.z;
		maxZ = upper.z;
		
		System.out.println(getBounds());
	}
	
	public double minZ, maxZ;
	public static int BOUNDING_CUBE_SIZE = 10;
}
